package com.xk.meeting.controller;

import com.xk.meeting.entity.User;
import com.xk.meeting.service.UserService;
import com.xk.meeting.service.UserServiceImpl;
import com.xk.meeting.utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String remember = request.getParameter("remember");
        String code = request.getParameter("code");
        HttpSession session = request.getSession();
        String sessionCode = (String)session.getAttribute("code");
        if(!(sessionCode != null && sessionCode.equalsIgnoreCase(code))){
            request.setAttribute("msg","验证码输入错误,请重新输入");
            request.getRequestDispatcher("login.jsp").forward(request,response);
            return;
        }
        UserService userService = new UserServiceImpl();
        User user = userService.login(username,password);
        if (user != null){
            if(remember != null){
                //创建了一个2个cookie,分别为(userKey,phone)(ssid,md5Encrypt(phone))
                CookieUtils.createCookies(username,request,response,60*60*24*7);
            }
            session.setAttribute("user",user);
            response.sendRedirect("index.jsp");
        }else{
            request.setAttribute("msg","账号或用户名错误,请重新输入");
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }
    }
}
